package com.wosai.teach.activity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.android.agoo.client.BaseRegistrar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.update.UmengUpdateAgent;
import com.wosai.teach.R;
import com.wosai.teach.adapter.NewPagerAdapter;
import com.wosai.teach.cst.AppCst;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.ExpType;
import com.wosai.teach.entity.MicroClassType;
import com.wosai.teach.listener.NewPageChangeListener;
import com.wosai.teach.pojo.Pic;
import com.wosai.teach.thread.LunBoRunnable;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.BitmapHelp;
import com.wosai.teach.utils.FixedSpeedScroller;
import com.wosai.teach.utils.OtherUtils;

@ContentView(R.layout.activity_main)
public class MainActivityBak extends AppActivity {

	@ViewInject(R.id.View_simulation)
	private LinearLayout linearLayout_simulation;
	@ViewInject(R.id.View_microClass)
	private LinearLayout linearLayout_microClass;
	@ViewInject(R.id.View_tk)
	private LinearLayout linearLayout_tk;

	// 沃赛仿真
	@ViewInject(R.id.button_simulation_1)
	private Button button_simulation_1;
	@ViewInject(R.id.button_simulation_2)
	private Button button_simulation_2;
	@ViewInject(R.id.button_simulation_3)
	private Button button_simulation_3;
	@ViewInject(R.id.button_simulation_4)
	private Button button_simulation_4;
	@ViewInject(R.id.button_simulation_5)
	private Button button_simulation_5;
	@ViewInject(R.id.button_simulation_6)
	private Button button_simulation_6;
	/**
	 * 沃赛仿真
	 */
	private List<Button> button_simulation = new ArrayList<Button>();
	/**
	 * 微课堂
	 */
	private List<Button> button_microClass = new ArrayList<Button>();

	// 微课堂
	@ViewInject(R.id.button_microClass_1)
	private Button button_microClass_1;
	@ViewInject(R.id.button_microClass_2)
	private Button button_microClass_2;
	@ViewInject(R.id.button_microClass_3)
	private Button button_microClass_3;
	@ViewInject(R.id.button_microClass_4)
	private Button button_microClass_4;
	@ViewInject(R.id.button_microClass_5)
	private Button button_microClass_5;
	// @ViewInject(R.id.button_microClass_6)
	// private Button button_microClass_6;

	// 题库
	@ViewInject(R.id.button_tk_hjjc)
	private Button button_tk_hjjc;
	@ViewInject(R.id.button_tk_djzy)
	private Button button_tk_djzy;

	private List<Pic> picList;
	private List<ExpType> expType;
	private List<MicroClassType> microClassType;

	@ViewInject(R.id.car_ll)
	private LinearLayout car_ll;
	@ViewInject(R.id.car_vg)
	private ViewGroup viewGroup;
	@ViewInject(R.id.car_vp)
	private ViewPager viewPager;
	private LunBoRunnable runnable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("沃赛教育");
		headRefresh(true);
		button_simulation.add(button_simulation_1);
		button_simulation.add(button_simulation_2);
		button_simulation.add(button_simulation_3);
		button_simulation.add(button_simulation_4);
		button_simulation.add(button_simulation_5);
		button_simulation.add(button_simulation_6);

		button_microClass.add(button_microClass_1);
		button_microClass.add(button_microClass_2);
		button_microClass.add(button_microClass_3);
		button_microClass.add(button_microClass_4);
		button_microClass.add(button_microClass_5);
		// button_microClass.add(button_microClass_6);

		UmengUpdateAgent.update(this);

		String device_token = BaseRegistrar.getRegistrationId(this);
		System.out.println("device_token||" + device_token);

		viewShow();

		simulationButtonShow();
		microClassButtonShow();

		changeTypeWidth();

	}

	/**
	 * 获取微课堂分类信息
	 */
	private void microClassButtonShow() {

		String url = AppCst.HTTP_URL_HOMEPAGE_MICROCLASSTYPE;
		System.out.println(url);

		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							microClassType = JSON.parseArray(result.getObject()
									.toString(), MicroClassType.class);
							if (OtherUtils.CheckNull(microClassType)) {
								for (int i = 0; i < 5; i++) {
									button_microClass.get(i).setVisibility(
											View.VISIBLE);
								}
							} else {
								int j = 0;
								for (MicroClassType mic : microClassType) {
									db.deleteAll(Selector
											.from(MicroClassType.class));
									db.save(mic);
									Button bb = button_microClass.get(j);
									bb.setVisibility(View.VISIBLE);
									bb.setText(mic.getName());
									j++;
									if (j >= 5) {
										break;
									}
								}
							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						for (int i = 0; i < 5; i++) {
							button_microClass.get(i)
									.setVisibility(View.VISIBLE);
						}
					}
				});

	}

	private void changeTypeWidth() {
		WindowManager wm = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		LayoutParams laParams = (LayoutParams) linearLayout_simulation
				.getLayoutParams();
		laParams.width = width * 1 / 4;
		linearLayout_simulation.setLayoutParams(laParams);
		linearLayout_microClass.setLayoutParams(laParams);
		linearLayout_tk.setLayoutParams(laParams);
	}

	/**
	 * 获取沃赛仿真分类信息
	 */
	private void simulationButtonShow() {

		String url = AppCst.HTTP_URL_EXPERIMENT_TYPE;
		System.out.println(url);

		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							expType = JSON.parseArray(result.getObject()
									.toString(), ExpType.class);
							if (OtherUtils.CheckNull(expType)) {
								for (int i = 0; i < 6; i++) {
									button_simulation.get(i).setVisibility(
											View.VISIBLE);
								}
							} else {
								int j = 0;
								for (ExpType home : expType) {
									db.deleteAll(Selector.from(ExpType.class));
									db.save(home);
									Button bb = button_simulation.get(j);
									bb.setVisibility(View.VISIBLE);
									bb.setText(home.getName());
									j++;
									if (j >= 6) {
										break;
									}
								}
							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						for (int i = 0; i < 6; i++) {
							button_simulation.get(i)
									.setVisibility(View.VISIBLE);
						}
					}
				});

	}

	private void viewShow() {

		int userId = 0;
		if (AppGlobal.user != null) {
			userId = AppGlobal.user.getUserId();
		}

		// 获取轮播图片
		String url = AppCst.HTTP_URL_PIC_LOGIN_HALL;
		url = url.replace("{userId}", userId + "");
		url = url.replace("{pageSize}", 5 + "");
		url = url.replace("{currentPage}", 1 + "");
		System.out.println(url);

		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							picList = JSON.parseArray(result.getObject()
									.toString(), Pic.class);
							exeCar();
							if (OtherUtils.CheckNull(picList)) {
								exeCar();
								return;
							}
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						exeCar();
					}
				});

	}

	protected void exeCar() {
		this.car_ll.setVisibility(View.VISIBLE);
		LayoutInflater layIn = LayoutInflater.from(getApplicationContext());
		List<View> viewList = new ArrayList<View>();
		if (OtherUtils.CheckNull(picList)) {
			int[] cars = { R.drawable.car1, R.drawable.car2, R.drawable.car3 };
			for (int car : cars) {
				View view = layIn.inflate(R.layout.activity_lun_item,
						viewPager, false);
				ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
				iv.setImageResource(car);
				iv.setScaleType(ScaleType.FIT_XY);
				viewList.add(view);
			}
		} else {
			for (Pic pic : picList) {
				View view = layIn.inflate(R.layout.activity_lun_item,
						viewPager, false);
				ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
				BitmapUtils bitmapUtils = BitmapHelp.getBitmapUtils(this);
				bitmapUtils.display(iv, pic.getUrl());
				// ImageLoaders.getInstance().displayImage(iv, pic.getUrl());
				iv.setScaleType(ScaleType.FIT_XY);
				viewList.add(view);
			}
		}

		NewPagerAdapter adapter = new NewPagerAdapter(viewList);
		viewPager.setAdapter(adapter);

		FixedSpeedScroller scroller = null;
		try {
			Field mField = ViewPager.class.getDeclaredField("mScroller");
			mField.setAccessible(true);
			scroller = new FixedSpeedScroller(viewPager.getContext(),
					new AccelerateInterpolator());
			mField.set(viewPager, scroller);
		} catch (Exception e) {
			e.printStackTrace();
		}

		ImageView[] imageViews = new ImageView[viewList.size()];
		for (int i = 0; i < viewList.size(); i++) {
			ImageView imageView = new ImageView(getApplicationContext());
			imageView.setLayoutParams(new LayoutParams(36, 16));
			imageView.setPadding(10, 0, 10, 0);// 左 上 右 下
			imageViews[i] = imageView;
			if (i == 0) {
				// 默认选中第一张图片
				imageViews[i].setImageResource(R.drawable.point_white);
			} else {
				imageViews[i].setImageResource(R.drawable.point_grey);
			}
			viewGroup.addView(imageViews[i]);
		}
		NewPageChangeListener listener = new NewPageChangeListener(imageViews);
		viewPager.setOnPageChangeListener(listener);

		Handler handler = new Handler();
		runnable = new LunBoRunnable(viewPager, viewList.size(), handler);
		runnable.setScroller(scroller);
		handler.postDelayed(runnable, 4000);

	}

	@Override
	protected void onDestroy() {
		System.exit(1);
		finish();
		super.onDestroy();
	}

	@OnClick(value = { R.id.View_simulation })
	public void View_simulationClick(View v) {
		System.out.println("=========点击沃赛仿真=========");
		// 仿真页面
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "0");
		startActivity(it);
	}

	@OnClick(value = { R.id.View_microClass })
	public void View_microClassClick(View v) {
		System.out.println("==========点击微课堂=========");
		Intent it = new Intent(this, MicroClassActivity.class);
		startActivity(it);
	}

	@OnClick(value = { R.id.View_tk })
	public void View_tkClick(View v) {
		System.out.println("==========点击题库==========");
	}

	@OnClick(value = { R.id.button_simulation_1 })
	public void button_simulation_hxjcClick(View v) {
		System.out.println("==========化学基础==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "1");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_simulation_4 })
	public void button_simulation_wljcClick(View v) {
		System.out.println("==========物理基础==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "4");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_simulation_2 })
	public void button_simulation_hxsbClick(View v) {
		System.out.println("==========化学设备==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "2");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_simulation_5 })
	public void button_simulation_wlyqClick(View v) {
		System.out.println("==========物理仪器==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "5");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_simulation_3 })
	public void button_simulation_hxsxClick(View v) {
		System.out.println("==========化学实训==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "3");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_simulation_6 })
	public void button_simulation_wlsxClick(View v) {
		System.out.println("==========物理实训==========");
		Intent it = new Intent(this, SimulationActivity.class);
		it.putExtra("type", "6");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_microClass_1 })
	public void button_microClass_1_cilck(View v) {
		System.out.println("==========微课堂1==========");
		Intent it = new Intent(this, MicroClassActivity.class);
		it.putExtra("type", "1");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_microClass_2 })
	public void button_microClass_2_Click(View v) {
		System.out.println("==========微课堂2==========");
		Intent it = new Intent(this, MicroClassActivity.class);
		it.putExtra("type", "2");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_microClass_3 })
	public void button_microClass_3_Click(View v) {
		System.out.println("==========微课堂3==========");
		Intent it = new Intent(this, MicroClassActivity.class);
		it.putExtra("type", "3");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_microClass_4 })
	public void button_microClass_4_Click(View v) {
		System.out.println("==========微课堂4==========");
		Intent it = new Intent(this, MicroClassActivity.class);
		it.putExtra("type", "4");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_microClass_5 })
	public void button_microClass_5_Click(View v) {
		System.out.println("==========微课堂5==========");
		Intent it = new Intent(this, MicroClassActivity.class);
		it.putExtra("type", "5");
		startActivity(it);
	}

	@OnClick(value = { R.id.button_tk_hjjc })
	public void button_tk_hjjcClick(View v) {
		System.out.println("==========环境监测==========");
	}

	@OnClick(value = { R.id.button_tk_djzy })
	public void button_tk_djzyClick(View v) {
		System.out.println("==========电机专业==========");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			AppUtil.AppOut(keyCode, event, this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
